import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def plot_adaptive_parameters():
    # 生成多样性值序列
    diversity_values = np.linspace(0, 1, 100)
    D_t = 0.3
    P_base_m = 0.01
    P_base_c = 0.8
    
    # 计算对应的变异率和交叉率
    mutation_rates = []
    crossover_rates = []
    
    for D in diversity_values:
        # 变异率计算
        if D < D_t:
            P_m = min(0.1, P_base_m * (1 + (D_t - D)))
        else:
            P_m = max(0.001, P_base_m * (1 - (D - D_t)))
        mutation_rates.append(P_m)
        
        # 交叉率计算
        if D < D_t:
            P_c = max(0.6, P_base_c * (1 - (D_t - D)))
        else:
            P_c = min(0.95, P_base_c * (1 + (D - D_t)))
        crossover_rates.append(P_c)
    
    # 设置matplotlib的中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    
    # 创建图表
    plt.figure(figsize=(12, 6))
    
    # 绘制变异率曲线
    plt.subplot(1, 2, 1)
    plt.plot(diversity_values, mutation_rates, 'b-', linewidth=2, label='变异率')
    plt.axvline(x=D_t, color='r', linestyle='--', label='多样性阈值')
    plt.xlabel('种群多样性')
    plt.ylabel('变异率')
    plt.title('自适应变异率曲线')
    plt.grid(True, linestyle='--', alpha=0.7)
    plt.legend(loc='best')
    
    # 绘制交叉率曲线
    plt.subplot(1, 2, 2)
    plt.plot(diversity_values, crossover_rates, 'g-', linewidth=2, label='交叉率')
    plt.axvline(x=D_t, color='r', linestyle='--', label='多样性阈值')
    plt.xlabel('种群多样性')
    plt.ylabel('交叉率')
    plt.title('自适应交叉率曲线')
    plt.grid(True, linestyle='--', alpha=0.7)
    plt.legend(loc='best')
    
    plt.tight_layout()
    plt.savefig('adaptive_parameters.png', dpi=300, bbox_inches='tight')
    plt.close()

def plot_diversity_tracking():
    try:
        # 读取DPGA结果文件
        results = pd.read_csv('DPGA_result.csv', header=None, names=['Generation', 'Fitness'])
        
        plt.figure(figsize=(10, 6))
        plt.plot(results['Generation'], results['Fitness'], 'b-', linewidth=2, label='最优适应度')
        plt.xlabel('迭代次数')
        plt.ylabel('适应度值')
        plt.title('种群适应度进化曲线')
        plt.grid(True, linestyle='--', alpha=0.7)
        plt.legend(loc='best')
        
        plt.tight_layout()
        plt.savefig('fitness_evolution.png', dpi=300, bbox_inches='tight')
        plt.close()
    except Exception as e:
        print(f"绘图过程中出现错误: {str(e)}")

if __name__ == "__main__":
    try:
        plot_adaptive_parameters()
        plot_diversity_tracking()
        print("绘图完成，请查看生成的图片文件。")
    except Exception as e:
        print(f"程序执行出错: {str(e)}")
